package com.empty.oredermenu.httpmannage;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by admin on 2017/1/3.
 * OkHttp请求
 */
public class OkHttpMannager {

    public OkHttpClient mOkHttpClient;
    private static OkHttpMannager mInstance;
    public static final MediaType mt = MediaType
            .parse("application/x-www-form-urlencoded; charset=utf-8");
    private final static int WHAT_CALLBACK = 1;

    private Call call;

//    private Context mcontext;
//    private int maxLoadTimes = 5;//总的连接次数
//    private int serversLoadTimes = 0;// 每次连接次数

    private OkHttpMannager() {

        mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(1800, TimeUnit.SECONDS)//读取超时
                .connectTimeout(1800, TimeUnit.SECONDS)//连接超时
                .writeTimeout(1800, TimeUnit.SECONDS)//写入超时
                .build();

    }

    public static OkHttpMannager getInstance() {
        if (mInstance == null) {
            synchronized (OkHttpMannager.class) {
                if (mInstance == null) {
                    mInstance = new OkHttpMannager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 异步的post请求
     *
     * @param url
    //	 * @param callback
     * @param params
     */
    public void _postAsyn(String url, Object params, Callback c) {
        call = mOkHttpClient.newCall(buildRequest(url, params));
        call.enqueue(c);
    }



    private Request buildRequest(String url, final Object _req) {
//        final MRequest req = (MRequest) _req;
//        String myurl = url + "?AppId=" + req.getAppId() + "&InterfaceName="
//                + req.getInterfaceName() + "&TimeStamp=" + req.getTimeStamp()
//                + "&signdata=" + req.getSignData();



        RequestBody requestBody = null;
        try {
            requestBody = RequestBody.create(mt, "");
        } catch (Exception e) {
            e.printStackTrace();
        }

        Request request = new Request.Builder()
                .url(url)
                .addHeader("Accept", "application/x-www-form-urlencoded")
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .post(requestBody).build();
        return request;
    }
    /***
     * 构造http请求
     *
     * @param url
     * @param params
     * @return
     */
    private Request buildRequest(String url, Object params, String type) {
        RequestBody requestBody = new FormBody.Builder()
                .add("search","Jurassic Park")
                .build();


        // Post请求类型
        if (type.equals("post")) {
            return new Request.Builder().url(url).post(requestBody).build();
        }
        // Get请求类型
        if (type.equals("get")) {
            Log.d("请求地址：", url);
            return new Request.Builder().url(url).build();
        }
        // Put请求类型
        if (type.equals("put")) {
            return new Request.Builder().url(url).put(requestBody).build();
        }
        // Delete请求类型
        if (type.equals("delete")) {
            return new Request.Builder().url(url).delete(requestBody).build();
        }
        return null;

    }

    /***
     * Post异步流请求
     *
     * @param /p
     * @param context
     */
    public void Post_Data(String urlutil,Object params, final Context context,
                          final OkHttp_CallResponse okHttp_callResponse, final boolean isshowtip
    , final String tag) {
//        mcontext = context;
        // 网络判断
//        if (!KexinAppliction.getIstance().isNetworkConnected()) {
//            StringCommon.String_Toast(context,"网络异常！请检测网络连接");
//            return;
//        }
        if (isshowtip) {
            // 开始加载
//            DialogCommon.getIstance().CreateMyDialog(context);
        }
        Log.v("orderhttp","   请求消息   ");

        OkHttpMannager.getInstance()._postAsyn(urlutil, params,
                new Callback() {
                    @Override
                    public void onFailure(final Call call, final IOException e) {

                        if (isshowtip) {
                            // 加载完毕
//                            DialogCommon.getIstance().MyDialogCanle();
                        }
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            public void run() {
                                // 需要在主线程的操作。

//                                LogTools.LogShowTool("请求超时"+e);
                                okHttp_callResponse.OkHttp_CallonFailure(call);


                            }
                        });
                    }

                    @Override
                    public void onResponse(final Call call, final Response response) throws IOException {
                        if (isshowtip) {
                            // 加载完毕
//                            LogTools.LogShowTool("   请求消息  码   "+response.code());
//                            DialogCommon.getIstance().MyDialogCanle();
                        }


                        if (response.isSuccessful()){
                            String msg = response.body().string();

                            Log.v("orderhttp","   请求消息   "+msg);

                            final JSONObject jsonObject = DataCommon.getIstance().jsonObjectXutils(msg);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                public void run() {
                                    // 需要在主线程的操作。
                                    try {
                                        if (!jsonObject.getString("RetCode").equals("0000")){
                                            //用户未登录处理  签名错误一样重新登录
                                            if (jsonObject.getString("RetCode").equals("0011")||jsonObject.getString("RetCode").equals("0007")){
                                                okHttp_callResponse.user_NoLogin();
                                                return;
                                            }

                                            //如果tag等于 电话记录查询 和 用户推出那么直接访问 成功接口
                                            if (tag.equals("callquery")||tag.equals("quite")){
                                                okHttp_callResponse.OkHttp_ResponseSuccse(call,response,jsonObject,tag);
                                            }else{
                                                okHttp_callResponse.OkHttp_ErrorCode(jsonObject.getString("RetCode"),tag);
//                                                ToastTools.getInsentence().Toast_Short(context,jsonObject.getString("RetMessage"));
                                            }
                                            return;
                                        }

                                        okHttp_callResponse.OkHttp_ResponseSuccse(call,response,jsonObject,tag);
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                }
                            });

                        }else{
                            if (isshowtip) {
                                // 加载完毕
//                                DialogCommon.getIstance().MyDialogCanle();
                            }
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                public void run() {
                                    // 需要在主线程的操作。

                                    okHttp_callResponse.OkHttp_CallonFailure(call);


                                }
                            });
                        }


                    }

                });
    }




    //取消一个网络请求
    public void Cancel_OkHttp(){
        if (mOkHttpClient != null){
            mOkHttpClient.dispatcher().cancelAll();
            if (call != null){
                call.cancel();
            }

        }
    }


    public void postAsynHttp(String urlutil, final Context context,
                              final OkHttp_CallResponse okHttp_callResponse, final boolean isshowtip
            , final String tag) {

        mOkHttpClient=new OkHttpClient();

        Request request = new Request.Builder()
                .url(urlutil)
                .get()
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                if (response.isSuccessful()){

                    String msg = response.body().string();
                    final JSONObject jsonObject = DataCommon.getIstance().jsonObjectXutils(msg);
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        public void run() {
                            // 需要在主线程的操作。
                            try {

                                okHttp_callResponse.OkHttp_ResponseSuccse(call,response,jsonObject,tag);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    });

                }
            }

        });
    }


}
